package cn.mall.order.utils;

import cn.mall.base.exception.UserBaseException;
import cn.mall.base.utils.AjaxResult;
import cn.mall.order.domain.Order;
import cn.mall.order.dto.FllowDto;
import cn.mall.order.dto.ToolDto;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

public class Utils {

    public static void main(String[] args) {
//
//        URL url = null;
//        try {
////            url = new URL("https://passport.weibo.com/visitor/genvisitor2");
//            String token = getSub(url);
//            String subValue = getSubValue(token);
//            String s = newData(subValue);
//            JSONObject jsonObject = new JSONObject(s);
//            String reposts_count = jsonObject.getString("reposts_count");
//            String comments_count = jsonObject.getString("comments_count");
//            String attitudes_count = jsonObject.getString("attitudes_count");
//            JSONObject page_info = jsonObject.getJSONObject("page_info");
//            JSONObject media_info = page_info.getJSONObject("media_info");
//            String online_users_number = media_info.getString("online_users_number");
//            System.out.println(online_users_number);
//        } catch (IOException | JSONException e) {
//            e.printStackTrace();
//        }


    }


    public static String newData(String s) throws IOException {
        String requestUrl = "https://weibo.com/ajax/statuses/show?id=Of3OImtor&locale=zh-CN";

        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求方法为GET
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br, zstd");
        connection.setRequestProperty("cookie","SUB="+s);

        // 连接并获取响应码
        connection.connect();
        int responseCode = connection.getResponseCode();
//        System.out.println("Response Code : " + responseCode);
        String charset = connection.getContentEncoding();
//        System.out.println(charset);
        // 读取响应内容
        BufferedReader in = null;
        in = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream()), "UTF-8"));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            //                System.out.println(in.readLine());
            response.append(inputLine);
        }
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


        // 打印响应内容
//        System.out.println(response.toString());

        // 关闭连接
        connection.disconnect();
        return response.toString();
    }




    public static  AjaxResult  ToolUtils(String url ){
        try {
            //公共工具类  判断该URL是否可以解析
            System.out.println("--------------------------------");
//            System.out.println(url);
            String s = Utils.dealStr(url);
//            System.out.println(s);
            String weiboData = getWeiboData(s);
            Map<Object, Object> objectObjectMap = parseWeiboData(weiboData);
            String reposts_count = (String) objectObjectMap.get("reposts_count");
            String comments_count = (String) objectObjectMap.get("comments_count");
            String attitudes_count = (String) objectObjectMap.get("attitudes_count");
            if(reposts_count==null || comments_count==null || attitudes_count==null){
                return AjaxResult.me().setSuccess(false);
            }
            String[] strings = {reposts_count, comments_count, attitudes_count};
            ArrayList<Integer> arrayList = convertToWan(strings);
            if(arrayList.size()==0){
                throw new UserBaseException(AjaxResult.me().setSuccess(false).setMessage("解析失败"));
            }
            if(arrayList.get(0)==null || arrayList.isEmpty()){
                throw new UserBaseException(AjaxResult.me().setSuccess(false).setMessage("解析失败"));
            }
            if(objectObjectMap.size() == 0){
                throw new UserBaseException(AjaxResult.me().setSuccess(false).setMessage("请检查URL是否符合格式要求!"));
            }
            for(int i =0;i<(arrayList.size());i++){
                if(arrayList.get(i) == null){
                    arrayList.set(i,0);
                }
            }
            return AjaxResult.me().setResultObj(arrayList);
        } catch (Exception e) {
            e.printStackTrace();
            throw new UserBaseException(AjaxResult.me().setSuccess(false).setMessage("基础数据处理失败"+e.getMessage()));
        }
    }



    public static ArrayList<Integer> convertToWan(String[] strs) {
        // 去掉"万"字
        ArrayList<Integer> arrayList = new ArrayList<>();
        for(String s:strs){
            if(s.contains("万")){
                if(s.contains("+")){
                    String numStr = s.replace("万+", "");
                    double num = Double.parseDouble(numStr);
                    int result = (int)(num*10000);
                    // 将浮点数乘以10000
                    arrayList.add(result);
                }
                else {
                    String numStr = s.replace("万", "");
                    // 将数字部分转换为浮点数
                    double num = Double.parseDouble(numStr);
                    int result = (int)(num*10000);
                    // 将浮点数乘以10000
                    arrayList.add(result);
                }

            }
            if(s.contains("百万")){
                String numStr = s.replace("百万", "");
                // 将数字部分转换为浮点数
                double num = Double.parseDouble(numStr);
                int result = (int)(num*1000000);
                // 将浮点数乘以1000000
                arrayList.add(result);
            }
            else if(!s.contains("万")){
                int i = Integer.parseInt(s);
                arrayList.add(i);
            }

        }
        if(arrayList.size()!=3){
            return new ArrayList<>();
        }
        return arrayList;

    }


    public static String getWeiboData(String url) {
        List<JSONObject> data = userIp();
        Random random = new Random();
        int randomIndex = random.nextInt(data.size());
        System.out.println("---------");
        System.out.println(data.get(randomIndex).toString());
        String proxyHost = null;
        try {
            proxyHost = data.get(randomIndex).get("ip").toString();
            String port = data.get(randomIndex).get("port").toString();
            Integer proxyPort = Integer.parseInt(port);
            String username = data.get(randomIndex).get("username").toString();
            String password = data.get(randomIndex).get("password").toString();
            Authenticator proxyAuthenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password.toCharArray());
                }
            };
            Authenticator.setDefault(proxyAuthenticator);
            Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyHost, proxyPort));

            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS) // 延长超时时间
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .proxy(proxy)
                    .build();

            Request request = new Request.Builder()
                    .url(url)
                    .build();
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body().string();
        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static Map<Object, Object> parseWeiboData(String html) throws JSONException {
        Map<Object, Object> map = new HashMap<>();
        Document document = Jsoup.parse(html);
//        System.out.println(document);
        Elements scriptElements = document.select("script");
        for (Element scriptElement : scriptElements) {
            String text = scriptElement.html();
            if (text.contains("$render_data")) {
                String[] vars = scriptElement.data().split("var ");
//                System.out.println(vars);
                String var = vars[2];
                var = var.replace("$render_data = [", "").replace("][0] || {};", "");
//                System.out.println(var);
                // 将处理后的字符串转换为JSONArray
                String trim = var.trim();
                JSONObject jsonObject = new JSONObject(trim);
                // 现在你可以访问jsonObject中的属性了
                JSONObject statusObject = jsonObject.getJSONObject("status");
                String reposts_count = statusObject.getString("reposts_count");
                String comments_count = statusObject.getString("comments_count");
                String attitudes_count = statusObject.getString("attitudes_count");
//                System.out.println("转发:"+reposts_count+",评论:"+comments_count+",点赞:"+attitudes_count);
                map.put("reposts_count",reposts_count);
                map.put("comments_count",comments_count);
                map.put("attitudes_count",attitudes_count);
            }
        }
        return map;
    }

    public static String dealStr(String str){
        String[] parts = str.split("\\?");
//        System.out.println(parts[0]);
        String part = parts[0];
        String[] split = part.split("/");
        if(split[2].contains("www.weibo.com") || split[2].contains("weibo.com")){
            split[2] = "m.weibo.cn";
        }
        String url = split[0]+"//"+split[2]+"/detail/"+split[4];
        return url;
    }

        public static String getSub(URL url) throws IOException
        {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            try {
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Accept", "*/*");
                connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36");
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                connection.setDoOutput(true);

                Map<String, String> params = new HashMap<>();
                params.put("cb", "visitor_gray_callback");
                params.put("tid", "");
                params.put("from", "weibo");

                StringBuilder postData = new StringBuilder();
                for (Map.Entry<String, String> param : params.entrySet()) {
                    if (postData.length() != 0) postData.append('&');
                    postData.append(encode(param.getKey())).append('=').append(encode(param.getValue()));
                }

                byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);
                connection.setFixedLengthStreamingMode(postDataBytes.length);

                try (java.io.OutputStream os = connection.getOutputStream()) {
                    os.write(postDataBytes);
                }

                int responseCode = connection.getResponseCode();
                if (responseCode >= 200 && responseCode < 300) {
                    try (BufferedReader br = new BufferedReader(
                            new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {

                        StringBuilder response = new StringBuilder();
                        String responseLine;
                        while ((responseLine = br.readLine()) != null) {
                            response.append(responseLine.trim());
                        }
                        return response.toString();
                    }
                } else {
                    throw new IOException("Unexpected response code: " + responseCode);
                }
            } finally {
                connection.disconnect();
            }

        }

        private static String encode(String s) {
            try {
                return java.net.URLEncoder.encode(s, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new AssertionError("编码解析有误", e);
            }
        }

    public static String getFllow() throws IOException {
        try {
            URL url = new URL("https://passport.weibo.com/visitor/genvisitor2");
            String token = getSub(url);
            return token;
        } catch (IOException e) {
            throw new IOException(e);
        }
    }

    public static String getSubValue(String s){

        // 使用正则表达式提取JSON字符串部分
        Pattern pattern = Pattern.compile("visitor_gray_callback\\((.*)\\);");
        Matcher matcher = pattern.matcher(s);
        if (matcher.find()) {
            String jsonString = matcher.group(1);

            // 使用Jackson库解析JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode rootNode = objectMapper.readTree(jsonString);
                JsonNode dataNode = rootNode.get("data");
                String subValue = dataNode.get("sub").asText();

                // 输出sub字段的值
//                System.out.println("sub字段的值: " + subValue);
                return subValue;
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
//            System.out.println("没有找到JSON部分");
            return null;
        }
        return null;
    }


    public static Integer getFollowdata(FllowDto fllowDto) throws IOException, JSONException {
        String s = dealStrFllow(fllowDto.getUrl());
        if(s==null){
            return null;
        }
        URL url = new URL(s);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        // 设置Cookie请求头
        String cookieValue = "SUB="+fllowDto.getSub(); // 替换为你的Cookie值
        connection.setRequestProperty("Cookie", cookieValue);

        // 执行请求并获取响应
        int responseCode = connection.getResponseCode();
//        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        Integer finaldata = getFinaldata(response.toString());
        // 输出响应内容
        return finaldata;
    }

    public static Integer getFinaldata(String s) throws JSONException {
        JSONObject jsonObject = new JSONObject(s);
        JSONObject dataObject = jsonObject.getJSONObject("data");

        // 获取"user"对象
        JSONObject userObject = dataObject.getJSONObject("user");

        // 获取"followers_count"字段的值
        return userObject.getInt("followers_count");
    }

    public static String dealStrFllow(String str){
        // 定义正则表达式来匹配/u/后面的数字
        String regex = "/u/(\\d+)";

        // 编译正则表达式
        Pattern pattern = Pattern.compile(regex);

        // 创建匹配器
        Matcher matcher = pattern.matcher(str);

        // 查找匹配项
        if (matcher.find()) {
            // 提取数字（组1的内容）
            String userId = matcher.group(1);

            // 输出提取到的数字
            return "https://weibo.com/ajax/profile/info?uid="+userId;
        }
        return null;

    }

    public static List<JSONObject> userIp(){
        List<JSONObject> dataList = new ArrayList<>();
        String filePath = "proxy.txt"; // 文本文件路径 D:\weibo_mall\src\main\resources\proxy.txt
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 假设每行数据都符合 "IP----端口----username----password----时间" 的格式
                //  \\|
                //  ----
                String[] parts = line.split("----");
                if (parts.length >=4) {
                    String ip = parts[0].trim();
                    String port = parts[1].trim();
                    String username = parts[2].trim();
                    String password = parts[3].trim();
                    // 忽略时间部分
                    // 创建JSONObject并添加到列表中
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("ip", ip);
                    jsonObject.put("port", port);
                    jsonObject.put("username", username);
                    jsonObject.put("password", password); // 注意：在实际应用中，避免存储或传输明文密码
                    dataList.add(jsonObject);
                }
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return dataList;
    }



}
